<?php

namespace yak\layui\behaviors;

use Yii;
use yii\base\ActionFilter;
use yii\web\HeaderCollection;
use yii\web\Request;
use yii\web\Response;

abstract class LayuiBehavior extends ActionFilter
{
    public function beforeAction($action)
    {
        $headers = Yii::$app->request->headers;
        $AOP = $headers->get('AOP', 0);
        if ($this->isActive($action) && $AOP == 1) {
            $request = Yii::$app->request;
            $params = call_user_func_array([$request, $request->method], []);
            $response = Yii::$app->response;
            $response->format = Response::FORMAT_JSON;
            $response->data = call_user_func_array([$this, 'run'], [$headers, $request, $params, $response]);
            $response->send();
            exit();
        }

        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    /**
     * @param HeaderCollection $headers
     * @param Request $request
     * @param array $params
     * @param Response $response
     * @return array
     */
    abstract public function run(HeaderCollection $headers, Request $request, array $params, Response $response);

    public function __call($name, $params)
    {
        return $this->fail('not found action');
    }

    protected function success($msg)
    {
        return ["code" => 0, "msg" => $msg];
    }

    protected function fail($msg)
    {
        return ['code' => 1, 'msg' => $msg];
    }

    protected function successData($data, $count)
    {
        return ["code" => 0, "msg" => "", "count" => $count, "data" => $data];
    }

    protected function successExcel($data, $header)
    {
        return ["code" => 0, "msg" => "", "data" => $data, "header" => $header];
    }


}